/*
 * @Description:
 * @Author:  huangshuai
 * @Date: 2023-10-16 16:29:27
 * @LastEditTime: 2023-12-27 14:48:48
 * @LastEditors: huangshuai
 */
import axios from "axios";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/stores/user";
const userStore = useUserStore();
enum RequestEnums {
  TIMEOUT = 5000,
}

// interface Result {
//   code: number;
//   msg: string;
// }
// interface ResultData<T = any> extends Result {
//   data?: T;
// }
const config = {
  // 默认地址
  baseURL: "http://139.159.149.18:8086/api",
  // baseURL: "http://localhost:5137/api",
  // baseURL: "/api",
  // 设置超时时间
  timeout: RequestEnums.TIMEOUT as number,
  // 跨域时候允许携带凭证
  withCredentials: true,
};
class RequestHttp {
  // 定义成员变量并指定类型
  service: any;
  public constructor(config: any) {
    // 实例化axios
    this.service = axios.create(config);
    this.service.interceptors.request.use(
      (config: any) => {
        return {
          ...config,
        };
      },
      (error: any) => {
        // 请求报错
        Promise.reject(error);
      }
    );

    /**
     * 响应拦截器
     * 服务器换返回信息 -> [拦截统一处理] -> 客户端JS获取到信息
     */
    this.service.interceptors.response.use(
      (response: any) => {
        return response.data;
      },
      (error: any) => {
        setTimeout(() => {
          userStore.loading = false;
          ElMessage.error(error.response.data.message);
        }, 500);
      }
    );
  }

  // 常用方法封装
  get(url: string, params?: object): Promise<any> {
    return this.service.get(url, { params });
  }
  post(url: string, params?: object): Promise<any> {
    return this.service.post(url, params);
  }
  put(url: string, params?: object): Promise<any> {
    return this.service.put(url, params);
  }
  delete(url: string, params?: object): Promise<any> {
    return this.service.delete(url, { params });
  }
  // get<T>(url: string, params?: object): Promise<ResultData<T>> {
  //   return this.service.get(url, { params });
  // }
  // post<T>(url: string, params?: object): Promise<ResultData<T>> {
  //   return this.service.post(url, params);
  // }
  // put<T>(url: string, params?: object): Promise<ResultData<T>> {
  //   return this.service.put(url, params);
  // }
  // delete<T>(url: string, params?: object): Promise<ResultData<T>> {
  //   return this.service.delete(url, { params });
  // }
}

// 导出一个实例对象
export default new RequestHttp(config) as any;
